package com.browsesoft.tools;

import java.util.Comparator;

import com.browsesoft.Entity;

/**
 * 实体比较器，可以根据实体的属性进行比较
 */
public class EntityComparator implements Comparator {
	/**
	 * 比较的方式
	 */
	public static int STRING_MODE = 0;

	public static int NUMBER_MODE = 1;

	/**
	 * 进行比较的属性
	 */
	private String name;

	/**
	 * 比较的方式
	 */
	private int type;

	public EntityComparator(String name, int type) {
		this.name = name;
		this.type = type;
	}

	public int compare(Object obj1, Object obj2) {
		// 得到实体属性
		Entity tool1 = (Entity) obj1;
		Entity tool2 = (Entity) obj2;
		String value1 = (String) tool1.getAttributes().get(this.name);
		String value2 = (String) tool2.getAttributes().get(this.name);
		// 为空者最小
		if ((value1 == null || value1.equals(""))
				&& (value2 != null && !value2.equals(""))) {
			return -1;
		} else if ((value2 == null || value2.equals(""))
				&& (value1 != null && !value1.equals(""))) {
			return 1;
		} else if ((value2 == null || value2.equals(""))
				&& (value1 == null || value1.equals(""))) {
			return 0;
		}
		// 按数字方式比较
		if (this.type == EntityComparator.NUMBER_MODE) {
			// 转换成数字进行比较
			int number1 = Integer.parseInt(value1);
			int number2 = Integer.parseInt(value2);
			return number1 - number2;
		}
		// 按字符方式进行比较
		return value1.compareTo(value2);
	}
}
